<!--
 * @Author: 梁卓
 * @Date: 2022-02-01 20:36:47
 * @LastEditTime: 2022-02-08 23:56:36
 * @LastEditors: Please set LastEditors
 * @Description: 用户管理页面
 * @FilePath: \dreamUi\src\views\system\user.vue
-->
<template>
  <div>
    <el-card>
        <el-row>
          <el-col :span="8">
            <el-input  v-model="queryInfo.queryString" clearable placeholder="Please input" @clear="findUser">
              <el-button icon="el-icon-search" slot="append" @click="findUser"></el-button>
            </el-input>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="insert" v-hasPermission="['USER_DELETE']">添加用户</el-button>
          </el-col>
      </el-row>
      <el-table  v-loading="loading" :data="tableData" style="width: 100%">
        <el-table-column type="index" label="序号"  />
        <el-table-column prop="username" label="用户名" />
        <el-table-column label="头像">
          <template slot-scope="scope">
            <el-image style="width: 50%;heigth: 50%;"
             :src="scope.row.avatar"
             :preview-src-list="preview(scope.row.avatar)" />
          </template>
        </el-table-column>
        <el-table-column label="角色标签">
          <template slot-scope="scope">
            <el-tag size="mini" v-for="(item,index) in scope.row.roles" :key="index">{{item.label}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sex" label="性别" :formatter="formatterSex"/>
        <el-table-column prop="phoneNumber" label="电话号码"/>
        <el-table-column prop="address" label="地址" show-overflow-tooltip/>
        <el-table-column  fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" circle size="small" v-hasPermission="['USER_UPDATE']" @click="updateUser(scope)" />
            <el-button type="danger" icon="el-icon-delete" circle size="small" v-hasPermission="['USER_DELETE']"  @click="deleteUser(scope)"/>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="total > 0"
        :currentPage="queryInfo.currentPage"
        :page-sizes="[8,15,30,50]"
        :page-size= "queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total= total
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>
    <!-- 权限的添加和修改 -->
    <el-dialog :title="title" :visible.sync="open" width="35%" @closed="dialogClose">
      <el-form :model="form" ref="form" :rules="rule">
        <el-row>
          <el-col :span="11">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选址性别">
            <el-option :value="0" label="男" />
            <el-option :value="1" label="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否是管理员" prop="admin">
          <el-radio-group v-model="form.admin">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-row>
          <el-col :span="22">
            <el-card>
              <div slot = "header" class = "clearfix">
                <span>选择对应的角色</span>
              </div>
              <el-tree
              ref = "tree"
               :data = "roleList"
                show-checkbox
                :check-strictly="true"
                node-key="id"
                :props="defaultProps"
                @check-change="treeChange"
              />
            </el-card>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="form.nickName" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="电话号码" prop="phoneNumber">
              <el-input v-model="form.phoneNumber"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeFrom">取 消</el-button>
        <el-button type="primary" @click="insertUser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'User',

  data() {
    return {
      // 分页
      queryInfo: {
        pageNumber: 1,
        pageSize: 8,
        queryString: ''
      },
      // 表格数据
      tableData: [],
      // 总条数
      total: 0,
      loading: true,
      // 添加或删除的标题
      title: '',
      // 是否打开对话框
      open: false,
      // 表单数据
      form: {
        userName: '',
        roles: {}
      },
      // 表单校验
      rule: {
        username:[
          {required: true, message: '请输入用户姓名', trigger: 'blur'},
          {min: 1, max: 50, message: '用户姓名的长度为1~50之间', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ],
        sex: [
          {required: true, message: '请选择性别', trigger: 'blur'}
        ],
        admin: [
          {required: true, message: '请选择是否为管理员', trigger: 'blur'}
        ],
        nickName: [
          {required: false, message: '请输入用户的昵称', trigger: 'change'},
          {min: 1, max: 50, message: '用户的昵称的长度为1~50之间', trigger: 'change'}
        ],
        phoneNumber: [
          {required: true, message: '请输入电话', trigger: 'change'}
        ],
        address: [
          {required: true, message: '请输入地址', trigger: 'change'},
          {min: 1, max: 50, message: '地址的长度为1~50之间', trigger: 'change'}
        ]
      },
      roleList: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      checkedRoles: []
    };
  },

  mounted() {
    
  },
  created() {
    this.findUser()
    this.findAllRoles()
  },
    methods: {
      // 查询所有角色信息
      findAllRoles () {
        this.$ajax.get('/role/findAllRoles').then(res => {
          this.roleList = res.data.data
        });
      },
    // 查询分页数据
    findUser() {
      this.$ajax.post('/user/findPage',this.queryInfo).then((res) => {
        this.tableData = res.data.rows
        this.total = res.data.total
        this.loading = false
      });
    },
    // 改变页码
    handleSizeChange(param) {
      this.queryInfo.pageSize = param;
      // 重新赋值
      this.findUser();
    },
    // 改变当前的页面
    handleCurrentChange(param) {
      this.queryInfo.pageNumber = param;
      this.findUser();
    },
    // 添加按钮事件
    insert(param) {
      this.title = '新增用户信息';
      this.open = true;
    },
    // 删除用户信息
    deleteUser(param) {
      this.$confirm(`您将永久删除-[${param.row.userName}]-的用户, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$ajax.delete(`/user/delete/${param.row.id}`).then((res) => {
            this.$message.success(res.data.message);
            // 防止删除最后一页中最后一个数据时无法换页的问题
            this.queryInfo.pageNumber = 1;
            // 删除成功后更新数据
            this.findUser();
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    // 关闭对话框事件
    dialogClose() {
      this.checkedRoles = []
      // 将整个表单进行重置
      this.$refs.form.resetFields();
      this.$refs.tree.setCheckedKeys([])
    },
    // 点击取消对话框
    closeFrom() { 
      this.checkedRoles = []
      this.form = {},
      this.open = false
      this.findUser()
    },
    // 修改用户信息
    updateUser(param) {
      this.form = param.row;
      this.checkedRoles = []
      param.row.roles.forEach(item => {
        this.checkedRoles.push(item)
      });
      this.$nextTick(() => {
        this.$refs.tree.setCheckedNodes(this.checkedRoles);
      });
      this.title = '修改用户信息';
      this.open = true;
    },
    // 添加用户
    insertUser(param) {
      this.$refs.form.validate(val => {
        // 校验不同通过
        if (!val) {
          return this.$message.error('表单校验不通过，请检查后提交')
        }
        // 判断是否时新增
        this.form.roles = this.checkedRoles
        if (this.form.id === undefined || this.form.id === null) {
          this.form.userName = this.form.username
          this.$ajax.post('/user/insert',this.form).then((res) => {
            this.$message.success(res.data.message);
            this.open = false;
            this.findUser();
          });
        } else {
          this.form.userName = this.form.username
          this.$ajax.put('/user/update',this.form).then((res) => {
            this.$message.success(res.data.message);
            this.open = false;
            this.findUser();
          });
        }
      });
    },
    // 头像预览
    preview(param) {
      let arr = []
      arr.push(param)
    },
    // 格式化性别
    formatterSex(row) {
      if (row.sex === 0) {
        return '男'
      }  else if (row.sex === 1){
        return '女'
      } else {
        return '未知'
      }
    },
    // 勾选的角色信息的回调
    // 菜单树形空间选中后的回调
    treeChange() {
      this.checkedRoles = []
      // 获取选中值de数据
     const checks = this.$refs.tree.getCheckedNodes(false,true);
     checks.forEach(item => {
       this.checkedRoles.push(item);
     });
    },
  }
};
</script>

<style lang="scss" scoped>

</style>